package com.gmall.item.service;

import com.gmall.common.bean.ResponseVo;
import com.gmall.item.feign.GmallPmsClient;
import com.gmall.item.feign.GmallSmsClient;
import com.gmall.item.feign.GmallWmsClient;
import com.gmall.item.vo.ItemVo;
import com.gmall.pms.entity.*;
import com.gmall.pms.vo.ItemGroupVo;
import com.gmall.pms.vo.SaleAttrValueVo;
import com.gmall.sms.vo.ItemSaleVo;
import com.gmall.wms.entity.WareSkuEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class ItemService {

    @Autowired
    private GmallPmsClient pmsClient;

    @Autowired
    private GmallSmsClient smsClient;

    @Autowired
    private GmallWmsClient wmsClient;

    @Autowired
    private ExecutorService executorService;

    @Autowired
    private TemplateEngine templateEngine;

    public ItemVo loadData(Long skuId) {

        ItemVo itemVo = new ItemVo();

        // 1.根据skuId查询sku  V
        CompletableFuture<SkuEntity> skuFuture = CompletableFuture.supplyAsync(() -> {
            ResponseVo<SkuEntity> skuEntityResponseVo = this.pmsClient.querySkuById(skuId);
            SkuEntity skuEntity = skuEntityResponseVo.getData();
            if (skuEntity == null) {
                throw new RuntimeException("你要访问的商品不存在！");
            }
            // 设置sku的基本参数
            itemVo.setSkuId(skuId);
            itemVo.setTitle(skuEntity.getTitle());
            itemVo.setSubtitle(skuEntity.getSubtitle());
            itemVo.setPrice(skuEntity.getPrice());
            itemVo.setDefaultImage(skuEntity.getDefaultImage());
            itemVo.setWeight(skuEntity.getWeight());
            return skuEntity;
        }, executorService);

        // 2.根据三级分类id查询一二三级分类 V
        CompletableFuture<Void> categoryFuture = skuFuture.thenAcceptAsync(skuEntity -> {
            ResponseVo<List<CategoryEntity>> categoryResponseVo = this.pmsClient.queryCategoriesByCid3(skuEntity.getCategoryId());
            List<CategoryEntity> categoryEntities = categoryResponseVo.getData();
            itemVo.setCategories(categoryEntities);
        }, executorService);

        // 3.根据品牌id查询品牌 V
        CompletableFuture<Void> brandFuture = skuFuture.thenAcceptAsync(skuEntity -> {
            ResponseVo<BrandEntity> brandEntityResponseVo = this.pmsClient.queryBrandById(skuEntity.getBrandId());
            BrandEntity brandEntity = brandEntityResponseVo.getData();
            if (brandEntity != null) {
                itemVo.setBrandId(brandEntity.getId());
                itemVo.setBrandName(brandEntity.getName());
            }
        }, executorService);

        // 4.根据spuId查询spu V
        CompletableFuture<Void> spuFuture = skuFuture.thenAcceptAsync(skuEntity -> {
            ResponseVo<SpuEntity> spuEntityResponseVo = this.pmsClient.querySpuById(skuEntity.getSpuId());
            SpuEntity spuEntity = spuEntityResponseVo.getData();
            if (spuEntity != null) {
                itemVo.setSpuId(spuEntity.getId());
                itemVo.setSpuName(spuEntity.getName());
            }
        }, executorService);

        // 5.根据skuId查询营销信息（积分、满减、打折） V
        CompletableFuture<Void> salesFuture = CompletableFuture.runAsync(() -> {
            ResponseVo<List<ItemSaleVo>> salesResponseVo = this.smsClient.querySalesBySkuId(skuId);
            List<ItemSaleVo> itemSaleVos = salesResponseVo.getData();
            itemVo.setSales(itemSaleVos);
        }, executorService);

        // 6.根据skuId查询库存信息	V
        CompletableFuture<Void> stockFuture = CompletableFuture.runAsync(() -> {
            ResponseVo<List<WareSkuEntity>> wareResponseVo = this.wmsClient.queryWareSkuBySkuId(skuId);
            List<WareSkuEntity> wareSkuEntities = wareResponseVo.getData();
            if (!CollectionUtils.isEmpty(wareSkuEntities)) {
                itemVo.setStore(wareSkuEntities.stream().anyMatch(wareSkuEntity -> wareSkuEntity.getStock() - wareSkuEntity.getStockLocked() > 0));
            }
        }, executorService);

        // 7.根据skuId查询sku的图片列表	V
        CompletableFuture<Void> imagesFuture = CompletableFuture.runAsync(() -> {
            ResponseVo<List<SkuImagesEntity>> imagesResponseVo = this.pmsClient.queryImagesBySkuId(skuId);
            List<SkuImagesEntity> skuImagesEntities = imagesResponseVo.getData();
            itemVo.setImages(skuImagesEntities);
        }, executorService);

        // 8.根据spuId查询spu下所有sku的销售属性  V
        CompletableFuture<Void> saleAttrsFuture = skuFuture.thenAcceptAsync(skuEntity -> {
            ResponseVo<List<SaleAttrValueVo>> saleAttrsResponseVo = this.pmsClient.querySaleAttrValuesBySpuId(skuEntity.getSpuId());
            List<SaleAttrValueVo> saleAttrValueVos = saleAttrsResponseVo.getData();
            itemVo.setSaleAttrs(saleAttrValueVos);
        }, executorService);

        // 9.根据skuId查询当前sku的销售属性	V  {3: 暗夜黑, 4: 8G, 5: 512G}
        CompletableFuture<Void> saleAttrFuture = CompletableFuture.runAsync(() -> {
            ResponseVo<List<SkuAttrValueEntity>> saleAttrResponseVo = this.pmsClient.querySaleAttrValusBySkuId(skuId);
            List<SkuAttrValueEntity> skuAttrValueEntities = saleAttrResponseVo.getData();
            if (!CollectionUtils.isEmpty(skuAttrValueEntities)) {
                Map<Long, String> map = skuAttrValueEntities.stream().collect(Collectors.toMap(SkuAttrValueEntity::getAttrId, SkuAttrValueEntity::getAttrValue));
                itemVo.setSaleAttr(map);
            }
        }, executorService);

        // 10.根据spuId查询当前spu下所有销售属性组合与skuId的映射关系 V
        CompletableFuture<Void> mappingFuture = skuFuture.thenAcceptAsync(skuEntity -> {
            ResponseVo<String> stringResponseVo = this.pmsClient.queryMappingBySpuId(skuEntity.getSpuId());
            String json = stringResponseVo.getData();
            itemVo.setSkuJsons(json);
        }, executorService);

        // 11.根据spuId查询spu的图片列表	V
        CompletableFuture<Void> spuImagesFuture = skuFuture.thenAcceptAsync(skuEntity -> {
            ResponseVo<SpuDescEntity> spuDescEntityResponseVo = this.pmsClient.querySpuDescById(skuEntity.getSpuId());
            SpuDescEntity spuDescEntity = spuDescEntityResponseVo.getData();
            if (spuDescEntity != null) {
                itemVo.setSpuImages(Arrays.asList(StringUtils.split(spuDescEntity.getDecript(), ",")));
            }
        }, executorService);

        // 12.根据分类Id查询规格参数分组及分组下的规格参数和值 V
        CompletableFuture<Void> groupFuture = skuFuture.thenAcceptAsync(skuEntity -> {
            ResponseVo<List<ItemGroupVo>> groupResponseVo = this.pmsClient.queryGroupWithAttrAndValueByCidAndSpuIdAndSkuId(skuEntity.getCategoryId(), skuEntity.getSpuId(), skuId);
            List<ItemGroupVo> itemGroupVos = groupResponseVo.getData();
            itemVo.setGroups(itemGroupVos);
        }, executorService);

        CompletableFuture.allOf(categoryFuture, brandFuture, spuFuture, salesFuture, stockFuture, imagesFuture, saleAttrsFuture,
                saleAttrFuture, mappingFuture, spuImagesFuture, groupFuture).join();
        // 异步生成静态页面
        executorService.execute(() -> {
            generateHtml(itemVo);
        });
        return itemVo;
    }

    private void generateHtml(ItemVo itemVo) {
        try (PrintWriter printWriter = new PrintWriter("D:\\static\\" + itemVo.getSkuId() + ".html")) {
            // 初始化上下文对象，并通过该对象向模板传递参数
            Context context = new Context();
            context.setVariable("itemVo", itemVo);
            // 生成静态页面的方法：1-模板名称 2-上下文对象
            this.templateEngine.process("item", context, printWriter);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {

//        CompletableFuture.runAsync(() -> {
//            System.out.println("2子线程程序：" + Thread.currentThread().getName());
//        });

        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("1子线程程序：" + Thread.currentThread().getName());
//            int i = 1/0;
            return "hello CompletableFuture";
        });
        CompletableFuture<String> future1 = future.thenApplyAsync(t -> {
            System.out.println("2==================thenApplyAsync====================");
            try {
                TimeUnit.SECONDS.sleep(4);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("2获取上一个任务的返回结果集: " + t);
            return "hello thenApplyAsync";
        });
        CompletableFuture<Void> future2 = future.thenAcceptAsync(t -> {
            System.out.println("3==================thenAcceptAsync====================");
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("3获取上一个任务的返回结果集: " + t);
        });
        CompletableFuture<Void> future3 = future.thenRunAsync(() -> {
            System.out.println("4==================thenRunAsync====================");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("1不获取上一个任务的返回结果集，也米有自己的返回结果集");
        });
        CompletableFuture.anyOf(future1, future2, future3).join();

//                .whenCompleteAsync((t, u) -> {
//            System.out.println("3==================whenCompleteAsync===================");
//            System.out.println("上一个任务的返回结果集t: " + t);
//            System.out.println("上一个任务的异常信息u: " + u);
//        }).exceptionally(t -> {
//            System.out.println("4==================exceptionally===================");
//            System.out.println("上一个任务的异常信息t: " + t);
//            return null;
//        });

//        ExecutorService executor = new ThreadPoolExecutor(10, 15, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10));
//        executor.submit(() -> {
//            System.out.println("2子线程程序：" + Thread.currentThread().getName());
//        });

//        new Thread(() -> {
//            System.out.println("4子线程程序：" + Thread.currentThread().getName());
//        }).start();
//        FutureTask<String> futureTask = new FutureTask<>(() -> {
//            System.out.println("2子线程程序：" + Thread.currentThread().getName());
////            TimeUnit.SECONDS.sleep(5);
////            int i = 1/0;
//            return "hello Callable...";
//        });
//        new Thread(futureTask).start();
//        while (!futureTask.isDone()) {
//            System.out.println("子任务没有执行完======");
//        }
//        try {
//            // 阻塞方式获取子任务的返回结果集
//            System.out.println("3子任务的返回结果集：" + futureTask.get());
//        } catch (Exception e) {
//            System.out.println("4子任务的异常信息：" + e.getMessage());
//        }
        System.out.println("1这是main方法线程：" + Thread.currentThread().getName());
        System.in.read();
    }
}

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("2子线程程序：" + Thread.currentThread().getName());
    }
}

class MyRunnable implements Runnable {

    @Override
    public void run() {
        System.out.println("3子线程程序：" + Thread.currentThread().getName());
    }
}